<template>
    <div class="info-page">
        <!-- 搜索 -->
        <el-form ref="queryForm" :model="queryFormModel" :inline="true">
            <el-form-item label="游戏标题">
                <el-input
                    placeholder="请输入标题"
                    v-model="queryFormModel.title"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="addGame">新增游戏</el-button>
                <el-button type="primary" @click="onSearch"> 查询 </el-button>
                <el-button @click="resetSearchForm"> 重置 </el-button>
            </el-form-item>
        </el-form>
        <div class="table-content">
            <el-table :data="tableData" border style="width: 100%">
                <el-table-column prop="id" label="游戏ID" width="80" />
                <el-table-column prop="title" label="游戏标题" width="180" />
                <el-table-column prop="typeName" label="游戏分类" width="180" />
                <el-table-column prop="drawingUrl" label="游戏图片" width="180">
                    <template #default="scope">
                        <img :src="scope.row.drawingUrl" width="100" />
                    </template>
                </el-table-column>
                <el-table-column
                    prop="createTime"
                    label="创建时间"
                ></el-table-column>
                <el-table-column
                    prop="updateTime"
                    label="更新时间"
                ></el-table-column>
                <el-table-column prop="status" label="状态">
                    <template #default="scope">
                        <el-tag v-if="scope.row.status === 1" type="success"
                            >已上架</el-tag
                        >
                        <el-tag v-if="scope.row.status === 2" type="warning"
                            >已下架</el-tag
                        >
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="280px">
                    <template #default="scope">
                        <el-button
                            type="primary"
                            @click="editGame(scope.row)"
                            round
                        >
                            编辑
                        </el-button>
                        <el-button
                            v-if="scope.row.status === 2"
                            type="primary"
                            @click="updateStatus(scope.row, '上架')"
                            round
                        >
                            上架
                        </el-button>
                        <el-button
                            v-if="scope.row.status === 1"
                            @click="updateStatus(scope.row, '下架')"
                            type="danger"
                            round
                        >
                            下架
                        </el-button>
                        <el-button
                            type="danger"
                            @click="delItem(scope.row)"
                            round
                        >
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination-box">
                <el-pagination
                    background
                    layout="prev, pager, next"
                    @current-change="changePage"
                    :total="total"
                />
            </div>
        </div>
        <!-- 新增和编辑弹窗 -->
        <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="40%">
            <div class="dialog-content">
                <el-form
                    :model="infoForm"
                    :rules="rules"
                    ref="infoFormRef"
                    label-width="120px"
                >
                    <el-form-item label="游戏名称" prop="title">
                        <el-input
                            style="width: 250px"
                            v-model="infoForm.title"
                            placeholder="请填写游戏名称"
                            autocomplete="off"
                        />
                    </el-form-item>
                    <el-form-item label="游戏描述" prop="introduce">
                        <el-input
                            type="textarea"
                            style="width: 250px"
                            v-model="infoForm.introduce"
                            placeholder="请填写游戏名称"
                            autocomplete="off"
                        />
                    </el-form-item>
                    <el-form-item label="游戏作者" prop="author">
                        <el-input
                            style="width: 250px"
                            v-model="infoForm.author"
                            placeholder="请填写游戏作者"
                            autocomplete="off"
                        />
                    </el-form-item>
                    <el-form-item label="游戏价格" prop="price">
                        <el-input
                            style="width: 250px"
                            v-model="infoForm.price"
                            placeholder="请填写游戏价格"
                            autocomplete="off"
                        />
                    </el-form-item>
                    <el-form-item label="游戏分类" prop="typeId">
                        <el-select
                            v-model="infoForm.typeId"
                            placeholder="请选择游戏分类"
                            size="large"
                            style="width: 200px"
                        >
                            <el-option
                                v-for="item in typeOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="收藏数" prop="collectionNum">
                        <el-input
                            style="width: 250px"
                            v-model="infoForm.collectionNum"
                            placeholder="请填写游戏收藏数"
                            autocomplete="off"
                        />
                    </el-form-item>
                    <el-form-item label="评论数" prop="commentNum">
                        <el-input
                            style="width: 250px"
                            v-model="infoForm.commentNum"
                            placeholder="请填写游戏评论数"
                            autocomplete="off"
                        />
                    </el-form-item>
                    <el-form-item label="状态" prop="status">
                        <el-switch
                            v-model="infoForm.status"
                            width="100"
                            inline-prompt
                            active-text="上架"
                            inactive-text="下架"
                            :active-value="1"
                            :inactive-value="2"
                        />
                    </el-form-item>
                    <el-form-item label="游戏列表图" prop="drawingUrl">
                        <el-upload
                            name="avatar"
                            class="user-avatar-uploader"
                            :show-file-list="false"
                            :http-request="
                                ({ file }) => {
                                    handleUpload({ file }, 'drawingUrl')
                                }
                            "
                            :before-upload="
                                (file) => {
                                    beforeAvatarUpload(file, 'drawingUrl')
                                }
                            "
                        >
                            <img
                                v-if="infoForm.drawingUrl"
                                :src="infoForm.drawingUrl"
                                class="avatar"
                            />
                            <el-icon v-else class="user-avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="背景图" prop="backgroundUrl">
                        <el-upload
                            name="avatar"
                            class="user-avatar-uploader"
                            :show-file-list="false"
                            :http-request="
                                ({ file }) => {
                                    handleUpload({ file }, 'backgroundUrl')
                                }
                            "
                            :before-upload="
                                (file) => {
                                    beforeAvatarUpload(file, 'backgroundUrl')
                                }
                            "
                        >
                            <img
                                v-if="infoForm.backgroundUrl"
                                :src="infoForm.backgroundUrl"
                                class="avatar"
                            />
                            <el-icon v-else class="user-avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="游戏截图" prop="gameImgList">
                        <el-upload
                            name="avatar"
                            class="user-avatar-uploader"
                            v-model:file-list="fileList"
                            list-type="picture-card"
                            :limit="3"
                            :http-request="
                                ({ file }) => {
                                    handleUpload({ file }, 'gameImgList')
                                }
                            "
                            :before-upload="
                                (file) => {
                                    beforeAvatarUpload(file, 'gameImgList')
                                }
                            "
                            :on-remove="
                                (...args) => {
                                    onRemove('gameImgList', ...args)
                                }
                            "
                        >
                            <el-icon
                                class="user-avatar-uploader-icon"
                                v-if="fileList.length < 3"
                            >
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogFormVisible = false"
                        >取消</el-button
                    >
                    <el-button type="primary" @click="handleConfirm">
                        保存
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, onMounted } from 'vue'
import {
    getAllGameList,
    getUploadToken,
    delGame,
    getGameSaveOrUpdate,
    getGameTypeList,
    updateGameStatus
} from '@/api/game'
import { format } from '@/utils'
import * as qiniu from 'qiniu-js'
import { QINIU_URL } from '@/utils/config'
const queryForm = ref(null)
const total = ref(0)
const tableData = ref([])
const typeOptions = ref([])
const fileList = ref([])
const qiniuToken = ref('')
const dialogFormVisible = ref(false)
const dialogTitle = ref('新增游戏')
const infoFormRef = ref(null)
const infoForm = ref({
    title: '',
    introduce: '',
    drawingUrl: '',
    backgroundUrl: '',
    status: 1,
    author: '',
    typeId: null,
    commentNum: '',
    collectionNum: '',
    price: '',
    gameImgList: []
})
const rules = {
    title: [{ required: true, message: '请填写游戏标题', trigger: 'blur' }],
    introduce: [{ required: true, message: '请填写游戏描述', trigger: 'blur' }],
    drawingUrl: [
        { required: true, message: '请上传游戏图片', trigger: 'blur' }
    ],
    backgroundUrl: [
        { required: true, message: '请上传游戏背景图', trigger: 'blur' }
    ],
    gameImgList: [
        { required: true, message: '请上传游戏背景图', trigger: 'blur' }
    ],
    author: [{ required: true, message: '请填写游戏作者', trigger: 'blur' }],
    typeId: [{ required: true, message: '请选择游戏分类', trigger: 'blur' }],
    commentNum: [
        { required: true, message: '请填写游戏评论数', trigger: 'blur' }
    ],
    collectionNum: [
        { required: true, message: '请填写游戏收藏数', trigger: 'blur' }
    ]
}
let page = 1,
    size = 20
const queryFormModel = ref({
    title: ''
})
const onSearch = () => {
    page = 1
    getList()
}
const addGame = () => {
    dialogTitle.value = '新增游戏'
    infoForm.value = {
        title: '',
        introduce: '',
        drawingUrl: '',
        backgroundUrl: '',
        status: 1,
        author: '',
        typeId: null,
        commentNum: '',
        collectionNum: '',
        price: '',
        gameImgList: []
    }
    fileList.value = []
    dialogFormVisible.value = true
}
const editGame = (item) => {
    infoForm.value = { ...item }
    dialogTitle.value = '编辑游戏'
    const imglist =
        item.gameImgList && item.gameImgList.length
            ? item.gameImgList.slice(0, 3)
            : item.gameImgList
    fileList.value = imglist.map((r) => {
        const arr = r.split('/image/')
        return {
            url: r,
            name: arr[1]
        }
    })
    infoFormRef.value && infoFormRef.value.resetFields()
    dialogFormVisible.value = true
}
const resetSearchForm = () => {
    queryFormModel.value.title = ''
    page = 1
    getList()
}
const changePage = (pageNum) => {
    page = pageNum
    getList()
}
const delItem = ({ id }) => {
    ElMessageBox({
        title: '提示',
        message: '是否要删除这条数据?',
        type: 'warning',
        showCancelButton: true
    }).then(() => {
        delGame({ id }).then((res) => {
            console.log('delGameType: ', res)
            ElMessage.success('删除成功！')
            resetSearchForm()
        })
    })
}
const updateStatus = ({ id, status }, str) => {
    ElMessageBox({
        title: '提示',
        message: `是否${str}要这条数据?`,
        type: 'warning',
        showCancelButton: true
    }).then(() => {
        updateGameStatus({ id, status: status === 1 ? 2 : 1 }).then((res) => {
            console.log('delGameType: ', res)
            ElMessage.success(str + '成功！')
            resetSearchForm()
        })
    })
}

const handleConfirm = () => {
    infoFormRef.value.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            const params = infoForm.value
            params.collectionNum = Number(params.collectionNum)
            params.commentNum = Number(params.commentNum)
            if (dialogTitle.value === '编辑游戏') {
                delete params.createTime
                delete params.updateTime
            }
            if (!params.typeName) {
                const item = typeOptions.value.find(
                    (r) => r.value === params.typeId
                )
                if (item) {
                    params.typeName = item.label
                }
            }
            getGameSaveOrUpdate(params).then((res) => {
                console.log('getGameSaveOrUpdate', res.data)
                if (!res.code) {
                    dialogFormVisible.value = false
                    ElMessage.success(dialogTitle.value + '成功！')
                    page = 1
                    getList()
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

async function getList() {
    try {
        const params = {
            pageNo: page,
            size,
            title: queryFormModel.value.title
        }
        const res = await getAllGameList(params)
        console.log(res)
        if (!res.code) {
            total.value = res.data.total
            const list = res.data.records || []
            list.forEach((r) => {
                // update_time
                if (r.createTime) {
                    r.createTime = format(r.createTime)
                }
                if (r.updateTime) {
                    r.updateTime = format(r.updateTime)
                }
            })
            tableData.value = list
        }
    } catch (error) {
        console.log(error)
    }
}
const beforeAvatarUpload = (file) => {
    const isType =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif'
    if (!isType) {
        ElMessage.error('头像只能是上传图片格式！')
        return false
    } else if (file.size / 1024 / 1024 > 5) {
        ElMessage.error('头像大小不能超过5MB!')
        return false
    }
    return true
}
const handleUpload = async ({ file }, valuekey) => {
    const putExtra = {}
    const config = {
        region: qiniu.region.z2
    }

    const observable = qiniu.upload(
        file,
        'image/' + file.name,
        qiniuToken.value,
        putExtra,
        config
    )
    const observer = {
        next(res) {
            console.log(res)
        },
        error(err) {
            console.log(err)
        },
        complete(res) {
            console.log(res)
            const { key } = res
            const imgUrl = `${QINIU_URL}/${key}`
            if (valuekey === 'gameImgList') {
                infoForm.value.gameImgList.push(imgUrl)
                // fileList.value.push({
                //     url: `${QINIU_URL}/${key}`,
                //     name: key
                // })
            } else {
                infoForm.value[valuekey] = imgUrl
            }
        }
    }
    const subscription = observable.subscribe(observer) // 上传开始
    console.log(subscription)
}
const onRemove = (valuekey, file) => {
    console.log(file)
    if (infoForm.value.gameImgList.length) {
        infoForm.value.gameImgList = infoForm.value.gameImgList.filter(
            (r) => r.indexOf(file.name) < -1
        )
    }
}
onMounted(async () => {
    const res = await getUploadToken()
    qiniuToken.value = res.data
    const typesRes = await getGameTypeList({
        pageNo: 1,
        size: 100
    })
    typeOptions.value = typesRes.data.records.map((r) => {
        return {
            value: r.id,
            label: r.name
        }
    })
    console.log('getGameTypeList: ', typesRes)
    console.log('getUploadToken: ', res.data)
    getList()
})
</script>
<style>
.el-icon.user-avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 140px;
    height: 140px;
    border: 1px solid #8c939d;
    text-align: center;
}
.dialog-content {
    height: 450px;
    overflow-y: auto;
}
.el-upload--picture-card {
    border: none;
    background-color: #fff;
}
</style>
<style scoped>
.pagination-box {
    margin-top: 20px;
    padding-left: 50px;
}
.tips {
    padding: 10px 0;
    font-size: 20px;
    margin-bottom: 20px;
}
.user-avatar-uploader .avatar {
    width: 140px;
    height: 140px;
    display: block;
}
</style>
